<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

/**
 * @property-read \Illuminate\Notifications\DatabaseNotificationCollection|\Illuminate\Notifications\DatabaseNotification[] $notifications
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\AdminMenus newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\AdminMenus newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\AdminMenus query()
 * @mixin \Eloquent
 */
class AdminAdmin extends Model
{

    protected $table = 'admin_admin';
    public $timestamps = false;

    /**
     * 管理员登陆
     * @param $username
     * @param $password
     * @param string $ip
     * @return bool
     */
    public static function login($username, $password, $ip = '')
    {
        $admin = static::where(['username' => $username])->first();
        if (is_null($admin)) {
            return false;
        }
        $passwordSecret   = static::getPassword($password, $admin->secret);
        $log['adminname'] = $username;
        $log['logintime'] = $_SERVER['REQUEST_TIME'];
        $log['loginip']   = $ip;
        if ($passwordSecret == $admin->password) { // 登陆成功
            $log['password']    = '***';
            $log['loginresult'] = 1;
            $log['cause']       = '登陆成功';
            session([
                'admin_id'        => $admin->id,
                'admin_logintime' => $_SERVER['REQUEST_TIME'],
                'admin_username'  => $username,
                'admin_roleid'    => $admin->roledid
            ]);
            AdminLoginLog::insert($log);
            return $admin->id;
        } else {
            $log['password']    = $password;
            $log['loginresult'] = 0;
            $log['cause']       = '登陆失败';
            AdminLoginLog::insert($log);
            return false;
        }
    }

    /**
     * 修改密码
     * @param bool $password
     * @param int $id
     * @param int $roleid
     * @return bool
     */
    public static function edit($username, $password = false, $id = 1, $roleid = 1)
    {
        $bind['roleid'] = $roleid;
        if ($password) {
            // 密码加密
            $secret           = static::createSecret();
            $password         = static::getPassword($password, $secret);
            $bind['password'] = $password;
            $bind['secret']   = $secret;
            $bind['username'] = $username;
        } else {
            $bind['username'] = $username;
        }
        return static::where(['id' => $id])->update($bind);
    }


    /**
     * 获取加密密码
     * @param $password
     * @param $secret
     * @return string
     */
    private static function getPassword($password, $secret)
    {
        return sha1(md5($password) . $secret);
    }

    /**
     * 生成secret
     * @param string $key
     * @return [type]
     */
    private static function createSecret($key = '')
    {
        return strtolower(md5($key . uniqid(true)));
    }
}
